package com.anjie.powerproject.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anjie.powerproject.entity.*;
import com.anjie.powerproject.pojo.CustomEdgeMulti;
import com.anjie.powerproject.pojo.CustomRelationshipCom;
import com.anjie.powerproject.service.*;
import com.anjie.powerproject.entity.RelationshipCom;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("relationshipCom")
public class RelationshipComController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RelationshipService relationshipService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private EnergyTypeService energyTypeService;
    @Autowired
    private RelationshipComService relationshipComService;


    /**
     * 跳转到编辑边页面
     */
    @PostMapping("/edgeEditMulti")
    @ResponseBody
    public JSONArray editPage(Integer stgyCode) {
        List<CustomRelationshipCom> relationshipComList = relationshipComService.findCustomRelationshipComListByStgyCode(stgyCode);
        List<CustomEdgeMulti> customEdgeMultiList = relationshipComService.findCustomEdgeMulti(relationshipComList);
        String string = JSON.toJSON(customEdgeMultiList).toString();
        com.alibaba.fastjson.JSONArray jsonArray = JSONObject.parseArray(string);
        return jsonArray;
    }

    /**
     * 跳转到添加组合策略页面
     */
    @PostMapping("/edgeAddMulti")
    @ResponseBody
    public JSONArray addPage(Integer deviceTo,Integer graphId) {
        List<Relationship> relationshipList = relationshipService.findCustomRelationshipByDeviceFromAndGraphId(deviceTo,graphId);
        String string = JSON.toJSON(relationshipList).toString();
        com.alibaba.fastjson.JSONArray jsonArray = JSONObject.parseArray(string);
        return jsonArray;
    }


    /**
     * 获取指定源设备设备的所有基础策略(未使用）
     */
    @PostMapping("/queryDeviceFromEdge")
    @ResponseBody
    public JSONArray getEdgeByDeviceTo(Integer deviceFrom) {
        List<Relationship> edgeList = new ArrayList<>();
        edgeList = relationshipService.findRelationshipByDeviceTo(deviceFrom);
        String string = JSON.toJSON(edgeList).toString();
        JSONArray jsonArray = JSONObject.parseArray(string);
        return jsonArray;
    }

    /**
     * 添加组合策略
     *
     */
    @PostMapping("/addEdgeMulti")
    @ResponseBody
    public Map addRelationshipCom(@RequestBody JSONObject json) {
        JSONArray relationships = json.getJSONArray("relationships");
        Integer integer = json.getInteger("stgyCode");
        Integer stgyCode = json.getInteger("stgyCode");
        Map res = new HashMap();
        //int count;
        List<RelationshipCom> addList = new ArrayList<>();  //存放组合策略信息
        List<RelationshipCom> list = new ArrayList<>();
        List<String> duplicateList = new ArrayList<>();
        //表示修改
        if(stgyCode!=null) {
            list = relationshipComService.findRelationshipComByStgyCode(stgyCode);
        }
        List<Integer> stgyCodeList = new ArrayList<>();
//        if (!list.isEmpty()) {
//            relationshipComService.deleteRelationshipComByStgyCode(stgyCode);
//        }
        //表示添加
        if(integer == null){
            if(relationshipComService.getMaxStgyCode()==null){
                stgyCode = 1;
            }else {
                stgyCode = relationshipComService.getMaxStgyCode() + 1;
            }
        }
        for (int i = 0; i < relationships.size(); i++) {
                JSONObject jsonObject = relationships.getJSONObject(i);
                RelationshipCom relationshipCom = new RelationshipCom();
                relationshipCom.setDeviceFrom(jsonObject.getInteger("deviceFrom"));
                relationshipCom.setDeviceTo(jsonObject.getInteger("deviceTo"));
//                relationshipCom.setLossRate(jsonObject.getFloat("lossRate"));
//                relationshipCom.setTypeId(jsonObject.getInteger("typeId"));
                relationshipCom.setGraphId(jsonObject.getInteger("graphId"));
                relationshipCom.setRelName(jsonObject.getString("relName"));
                relationshipCom.setWorkTime(json.getString("worktime"));
                relationshipCom.setStgyCode(stgyCode);
                addList.add(relationshipCom);
        }
        stgyCodeList = relationshipComService.findAllStgyCode();
        //如果源设备不一致，判断重复
        //工作时间不一致，判断策略不重复，但如果是添加的话，导致出现目标设备、源设备一致，但工作时间不同的策略
        //区分添加和修改
        boolean flag = false;
        if (integer == null) {  //添加
            //与数据库所有目标设备进行比较
            for(int j = 0;j < stgyCodeList.size(); j++) {
                List<RelationshipCom> relationshipComList =
                        relationshipComService.findRelationshipComByStgyCode(stgyCodeList.get(j));
                if (relationshipComList.get(0).getDeviceTo().equals(addList.get(0).getDeviceTo())) {
                    flag = true;
                    break;
                }
            }
        } else {   //修改
            flag = relationshipComService.checkStgyRepeat(addList);
        }

        if (flag) {
            duplicateList.add("组合策略重复，请核对后重新添加");
        }

        /*for(int j = 0;j < stgyCodeList.size(); j++){
            int count = 0;
            //设定策略是否重复的标志
            boolean flag = false;
            //找
            List<RelationshipCom> relationshipComList = relationshipComService.findRelationshipComByStgyCode(stgyCodeList.get(j));
            System.out.println(addList.get(0).getDeviceTo());
            System.out.println(relationshipComList.get(0).getDeviceTo());
            //这里原先思路是比较取出数据中与添加策略目标设备相同的策略进行比较，如果它们的源设备相同，进行计数
            if(addList.get(0).getDeviceTo().equals(relationshipComList.get(0).getDeviceTo())){

                for(RelationshipCom relationshipCom : addList){
                    for(RelationshipCom relationshipCom1 : relationshipComList){
                        System.out.println(relationshipCom.getDeviceFrom());
                        System.out.println(relationshipCom1.getDeviceFrom());
                        if(!relationshipCom.getDeviceFrom().equals(relationshipCom1.getDeviceFrom())) {
                            //当修改了源设备，判定策略重复
                            flag = true;
                            break;
                            //count++;
                            //break;
                        }
                    }
                    if (flag) break;
                    //if(count==0){break;}
                }
            }*/

            //表示只修改了时间, 判定策略重复
            /*if(count==addList.size()&&count==relationshipComList.size()){
                //duplicateList.add("组合策略重复，请核对后重新添加");
                //break;
                flag = true;
                break;
            }*/

            /*if (flag) {
                duplicateList.add("组合策略重复，请核对后重新添加");
                break;
            }*/
        if (!list.isEmpty()&&duplicateList.size()==0) {
            relationshipComService.deleteRelationshipComByStgyCode(stgyCode);
        }
        if (addList.size()>0&&duplicateList.size()==0) {
            relationshipComService.saveRelationshipComList(addList);
            res.put("status", "添加成功");
        } else {
            res.put("status", duplicateList.get(0));
        }
        return res;
    }

    /**
     * 根据组合编码获取组合策略
     */
    @PostMapping("/queryEdgeMulti")
    @ResponseBody
    public JSONArray getEdgeByStgyCode(Integer stgyCode) {
        List<CustomRelationshipCom> list = new ArrayList<>();
        list = relationshipComService.findCustomRelationshipComListByStgyCode(stgyCode);
        List<CustomEdgeMulti> customEdgeMulti = relationshipComService.findCustomEdgeMulti(list);
        String string = JSON.toJSON(customEdgeMulti).toString();
        JSONArray jsonArray = JSONObject.parseArray(string);
        return jsonArray;
    }

    /**
     * 删除组合策略
     */
    @PostMapping("/deleteEdgeMulti")
    @ResponseBody
    public String deleteRelationshipCom(Integer stgyCode) {
        List<RelationshipCom> relationshipComList = new ArrayList<>();
        relationshipComList = relationshipComService.findRelationshipComByStgyCode(stgyCode);
        if (relationshipComList.size() > 0) {
            relationshipComService.deleteRelationshipComByStgyCode(stgyCode);
            return "success";
        } else {
            return "faild";
        }
    }

    /**
     * 删除单条策略
     */
    @PostMapping("/deleteEdge")
    @ResponseBody
    public String deleteEdge(Integer deviceFrom, Integer deviceTo, Integer stgyCode) {
        List relationshipList = relationshipComService.findRelationshipComByDeviceFromAndToAndStgyCode(deviceFrom, deviceTo, stgyCode);
        if (relationshipList.size() > 0) {
            relationshipComService.deleteRelationshipComByDeviceFromAndToAndStgyCode(deviceFrom, deviceTo, stgyCode);
            return "success";
        } else {
            return "faild";
        }
    }


    /**
     * 跳转到所有边列表界面
     */
    @PostMapping("/viewRelationshipCom")
    @ResponseBody
    public Map viewRelationshipCom() {
        Map map = new HashMap();
        List relationshipComList = relationshipComService.findCustomRelationshipComList();
        List<Integer> stgyCodes = relationshipComService.findAllStgyCode();
        List<CustomEdgeMulti> customEdgeMultiList = new ArrayList<CustomEdgeMulti>();
        for(Integer stgyCode : stgyCodes){
            List<CustomRelationshipCom> list = new ArrayList<>();
            list = relationshipComService.findCustomRelationshipComListByStgyCode(stgyCode);
            List<CustomEdgeMulti> customEdgeMulti = relationshipComService.findCustomEdgeMulti(list);
            customEdgeMultiList.add(customEdgeMulti.get(0));
        }
        List graphInfoList = graphInfoService.getAllGraphInfo();
        String string1 = JSON.toJSON(customEdgeMultiList).toString();
        com.alibaba.fastjson.JSONArray jsonArrayRlist = JSONObject.parseArray(string1);
        String string2 = JSON.toJSON(graphInfoList).toString();
        com.alibaba.fastjson.JSONArray jsonArrayGlist = JSONObject.parseArray(string2);
        map.put("relationshipComList",jsonArrayRlist);
        map.put("graphInfoList",jsonArrayGlist);
        return map;
    }


    /**
     * 显示所有的组合策略编码
     */
    @PostMapping("/viewStgyCode")
    @ResponseBody
    public JSONArray viewStgyCode(){
        List<String> list = relationshipComService.findAllStgyCode();
        String string = JSON.toJSON(list).toString();
        com.alibaba.fastjson.JSONArray jsonArray = JSONObject.parseArray(string);
        return  jsonArray;

    }


    /**
     * 扩充组合策略的边
     */
    @PostMapping("/addEdge")
    @ResponseBody
    public Map addEdge(@RequestBody JSONObject json){
        JSONArray relationships = json.getJSONArray("relationships");
        Integer stgyCode = json.getInteger("stgyCode");
        Map res = new HashMap();
        List<RelationshipCom> addList = new ArrayList<>();
        for (int i = 0; i < relationships.size(); i++) {
            JSONObject jsonObject = relationships.getJSONObject(i);
            RelationshipCom relationshipCom = new RelationshipCom();
            relationshipCom.setDeviceFrom(jsonObject.getInteger("deviceFrom"));
            relationshipCom.setDeviceTo(jsonObject.getInteger("deviceTo"));
//            relationshipCom.setLossRate(jsonObject.getFloat("lossRate"));
//            relationshipCom.setTypeId(jsonObject.getInteger("typeId"));
            relationshipCom.setGraphId(jsonObject.getInteger("graphId"));
            relationshipCom.setRelName(jsonObject.getString("relName"));
            relationshipCom.setWorkTime(json.getString("worktime"));
            relationshipCom.setStgyCode(stgyCode);
            addList.add(relationshipCom);
        }
        if (addList.size() > 0) {
            relationshipComService.saveRelationshipComList(addList);
            res.put("status", "添加成功");
        } else {
            res.put("status", "添加失败" );
        }
        return res;
    }


    /**
     * 获取指定图谱的所有组合边
     * @param graphId
     * @param model
     * @return
     */
    @GetMapping("/viewRelationshipCom/{graphId}")
    public String viewRelationshipById(@PathVariable("graphId")Integer graphId, Model model){
        List<Integer> stgyCodes = relationshipComService.findAllStgyCodeByGraph(graphId);
        List customEdgeMultiList = new ArrayList<>();
        for(Integer stgyCode : stgyCodes){
            List<CustomRelationshipCom> list = new ArrayList<>();
            list = relationshipComService.findCustomRelationshipComListByStgyCode(stgyCode);
            List<CustomEdgeMulti> customEdgeMulti = relationshipComService.findCustomEdgeMulti(list);
            customEdgeMultiList.add(customEdgeMulti.get(0));
        }
        List graphInfoList = graphInfoService.getAllGraphInfo();
        model.addAttribute("relationshipComList",customEdgeMultiList);
        model.addAttribute("graphInfoList",graphInfoList);
        model.addAttribute("graphId",graphId);
        return "edgeMulti";
    }

    @PostMapping("/getDeviceList")
    @ResponseBody
    public Map getDeviceList(Integer graphId){
        List<Integer> list = relationshipComService.findDeviceToListByGrraphId(graphId);
        List<Device> deviceList = new ArrayList<>();
        Map map = new HashMap();
        for(Integer integer:list){
            Device device =deviceService.findDeviceById(integer);
            deviceList.add(device);
        }
        map.put("deviceList",deviceList);
        return map;
    }
}